import { useEffect } from 'react'
import { Form, Button, Input, Modal, NoticeBar } from 'antd-mobile'
import { observer, useLocalObservable } from 'mobx-react'
import NavBar from '@/components/Global/NavBar'
import styles from './index.module.less'
import Store from './store'
import type { ResetPwdParamsType } from '../api/interface'
import { PWD_HARD_RULES } from '@/utils/RegExps'
import { stores } from '@/stores'

export default observer(() => {
    const { updatePassword } = useLocalObservable(() => new Store())
    const { getUserInfo } = stores.userStore
    const [formInstance] = Form.useForm()
    const onSubmit = (values: ResetPwdParamsType) => {
        updatePassword(values)
    }

    const validator = (_: any, value: string) => {
        let new_password = formInstance.getFieldValue('new_password')
        if (!value) {
            return Promise.resolve()
        }
        if (new_password === value) {
            return Promise.resolve()
        } else {
            return Promise.reject('确认密码与新密码输入不一致')
        }
    }
    const isDefaultPassword = getUserInfo?.is_default_password === 1

    useEffect(() => {
        if (!isDefaultPassword) return
        Modal.alert({
            content: '请按照平台要求，完成“原始密码”修改后，再进行其他操作！',
        })
    }, [isDefaultPassword])

    /** 原始密码的校验规则 */
    // const originPwdRules = useMemo(() => {
    //     if (isDefaultPassword) {
    //         return [
    //             { required: true, message: '密码必填' },
    //             // { pattern: /^[0-9]{6}$/, message: '密码错误' },
    //         ]
    //     } else {
    //         return PWD_RULES
    //     }
    // }, [isDefaultPassword])

    /** 新密码的校验规则 */
    const newPwdRule = {
        validator: (_: any, value: string) => {
            const oldPwd = formInstance.getFieldValue('old_password')

            if (oldPwd === value) {
                return Promise.reject(new Error('请按要求更换其他密码'))
            } else {
                return Promise.resolve()
            }
        },
    }

    return (
        <div className={styles.page}>
            <NavBar title={'修改密码'} />
            {isDefaultPassword && (
                <NoticeBar
                    content="依照平台要求，用户需完成“原始密码”的修改后，方可正常使用平台功能。"
                    color="alert"
                    closeable
                />
            )}
            <div className={styles.formView}>
                <Form
                    style={{ '--border-top': 'none' }}
                    onFinish={onSubmit}
                    form={formInstance}
                    footer={
                        <Button block type="submit" className={styles.submitBtn}>
                            保存
                        </Button>
                    }
                >
                    <Form.Item
                        name="old_password"
                        label={'原始密码'}
                        // rules={[...originPwdRules, {}]}
                        rules={[{ required: true, message: '密码必填' }]}
                    >
                        <Input
                            maxLength={20}
                            onChange={() => {
                                if (formInstance.getFieldValue('new_password')) {
                                    formInstance.validateFields(['new_password'])
                                }
                            }}
                        />
                    </Form.Item>

                    <Form.Item
                        name="new_password"
                        label={'新密码'}
                        rules={[...PWD_HARD_RULES, newPwdRule]}
                    >
                        <div>
                            <Input type={'text'} />
                            <div className={styles.helper}>
                                长度8至20位，必须包含字母、数字、特殊字符
                            </div>
                        </div>
                    </Form.Item>
                    <Form.Item
                        name="confirm_password"
                        label={'确认密码'}
                        rules={[...PWD_HARD_RULES, { validator }]} //pattern
                    >
                        <div>
                            <Input type={'text'} />
                            <div className={styles.helper}>
                                长度8至20位，必须包含字母、数字、特殊字符
                            </div>
                        </div>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
})
